package org.androidpn.server.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SerializeUtil {

	private static final Log log = LogFactory.getLog(SerializeUtil.class);

	/**
	 * 对象序列化成String
	 * 
	 * @param object
	 * @return
	 */
	public static String object2String(Object object) {
		String objString = null;
		ByteArrayOutputStream baops = null;
		ObjectOutputStream oos = null;
		try {
			baops = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baops);
			oos.writeObject(object);
			byte[] bytes = baops.toByteArray();
			objString = new String(bytes);
		} catch (IOException e) {
			log.error(e.getMessage());
		} finally {
			try {
				if (oos != null)
					oos.close();
				if (baops != null)
					baops.close();
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
		return objString;
	}

	/**
	 * 对象反序列化
	 * 
	 * @param objString
	 *            对象序列化的字符串
	 * @param clazz
	 *            目标类
	 * @return
	 */
	public static <T extends Serializable> T getObjectFromString(
			String objString, Class<T> clazz) {
		byte[] bytes = objString.getBytes();
		ObjectInputStream ois = null;
		T obj = null;
		try {
			ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
			obj = (T) ois.readObject();
		} catch (IOException e) {
			log.error(e);
		} catch (ClassNotFoundException e) {
			log.error(e);
		} finally {
			try {
				if (ois != null)
					ois.close();
			} catch (IOException e) {
				log.error(e);
			}
		}

		return obj;
	}

}
